<route lang="json5">
{
  style: {
    navigationBarTitleText: '愿望清单'
  }
}
</route>

<script lang="ts" setup>
import type { WishItem } from '@/types/couple'
import dayjs from 'dayjs'
import { computed, onMounted, ref } from 'vue'
import { useToast } from 'wot-design-uni'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'

defineOptions({
  name: 'Wishlist',
})

const coupleStore = useSupabaseCoupleStore()
const { success: showSuccess } = useToast()

const showAddDialog = ref(false)
const showDatePicker = ref(false)
const showEditDatePicker = ref(false)
const activeTab = ref('all')
const newWish = ref<Partial<WishItem>>({
  title: '',
  description: '',
  category: 'other',
  priority: 'medium',
  status: 'pending',
  targetDate: '',
  cost: undefined,
})
// 用于日期选择器的临时变量（时间戳）
const tempTargetDate = ref(Date.now())

const categories = [
  { label: '旅行 ✈️', value: 'travel', icon: '✈️', color: '#ff69b4' },
  { label: '美食 🍰', value: 'food', icon: '🍰', color: '#ffb6c1' },
  { label: '活动 🎀', value: 'activity', icon: '🎀', color: '#ffc0cb' },
  { label: '礼物 🎁', value: 'gift', icon: '🎁', color: '#ff91a4' },
  { label: '其他 💖', value: 'other', icon: '💖', color: '#ffa0b4' },
]

const priorities = [
  { label: '低', value: 'low' },
  { label: '中', value: 'medium' },
  { label: '高', value: 'high' },
]

const tabs = [
  { label: '全部', value: 'all' },
  { label: '待实现', value: 'pending' },
  { label: '进行中', value: 'in-progress' },
  { label: '已完成', value: 'completed' },
]

// 过滤后的愿望清单
const filteredWishlist = computed(() => {
  let list = coupleStore.wishlist

  if (activeTab.value !== 'all') {
    list = list.filter(wish => wish.status === activeTab.value)
  }

  return list.sort((a, b) => {
    // 按优先级和创建时间排序
    const priorityOrder = { high: 3, medium: 2, low: 1 }
    const priorityDiff = priorityOrder[b.priority] - priorityOrder[a.priority]
    if (priorityDiff !== 0)
      return priorityDiff

    return dayjs(b.createdAt).diff(dayjs(a.createdAt))
  })
})

// 获取分类信息
function getCategoryInfo(category: string) {
  return categories.find(c => c.value === category) || categories[4]
}

// 获取优先级颜色
function getPriorityColor(priority: string) {
  const colors = {
    high: '#ff4757',
    medium: '#ffa502',
    low: '#2ed573',
  }
  return colors[priority as keyof typeof colors] || colors.medium
}

// 获取状态文本
function getStatusText(status: string) {
  const statusMap = {
    'pending': '待实现',
    'in-progress': '进行中',
    'completed': '已完成',
  }
  return statusMap[status as keyof typeof statusMap] || '待实现'
}

// 切换愿望状态
async function toggleWishStatus(wish: WishItem) {
  const statusFlow = {
    'pending': 'in-progress',
    'in-progress': 'completed',
    'completed': 'pending',
  }

  const newStatus = statusFlow[wish.status as keyof typeof statusFlow] as WishItem['status']
  await coupleStore.updateWish(wish.id, { status: newStatus })

  if (newStatus === 'completed') {
    showSuccess('恭喜！愿望实现了 🎉')
  }
}

// 处理日期选择
function handleDateConfirm() {
  const val = dayjs(tempTargetDate.value).format('YYYY-MM-DD')
  newWish.value.targetDate = val
  showDatePicker.value = false
}

function handleEditDateConfirm() {
  const val = dayjs(tempTargetDate.value).format('YYYY-MM-DD')
  editWish.value.targetDate = val
  showEditDatePicker.value = false
}

// 添加愿望
async function handleAddWish() {
  if (!newWish.value.title) {
    return
  }

  await coupleStore.addWish(newWish.value as Omit<WishItem, 'id' | 'createdAt' | 'updatedAt'>)

  // 重置表单
  newWish.value = {
    title: '',
    description: '',
    category: 'other',
    priority: 'medium',
    status: 'pending',
    targetDate: '',
    cost: undefined,
  }
  tempTargetDate.value = Date.now()

  showAddDialog.value = false
  showSuccess('愿望添加成功')
}

// 计算进度
function getProgress(status: string) {
  const progressMap = {
    'pending': 0,
    'in-progress': 50,
    'completed': 100,
  }
  return progressMap[status as keyof typeof progressMap] || 0
}

// 统计数据
const stats = computed(() => {
  const total = coupleStore.wishlist.length
  const pending = coupleStore.wishlist.filter(w => w.status === 'pending').length
  const doing = coupleStore.wishlist.filter(w => w.status === 'in-progress').length
  const done = coupleStore.wishlist.filter(w => w.status === 'completed').length
  return { total, pending, doing, done }
})

// 编辑/删除
const showEditDialog = ref(false)
const editingId = ref<string | null>(null)
const editWish = ref<Partial<WishItem>>({})

function openActions(wish: WishItem) {
  uni.showActionSheet({
    itemList: ['编辑', '删除', '取消'],
    success: (res) => {
      if (res.tapIndex === 0)
        beginEdit(wish)
      else if (res.tapIndex === 1)
        confirmRemove(wish)
    },
  })
}

function beginEdit(wish: WishItem) {
  editingId.value = wish.id
  editWish.value = { ...wish }
  // 设置编辑时的时间戳
  tempTargetDate.value = wish.targetDate ? dayjs(wish.targetDate).valueOf() : Date.now()
  showEditDialog.value = true
}

function closeEdit() {
  showEditDialog.value = false
  editingId.value = null
}

async function submitEdit() {
  if (!editingId.value)
    return
  await coupleStore.updateWish(editingId.value, editWish.value)
  showEditDialog.value = false
  editingId.value = null
  uni.showToast({ title: '已更新', icon: 'success' })
}

function confirmRemove(wish: WishItem) {
  uni.showModal({
    title: '删除确认',
    content: `确定删除“${wish.title}”吗？`,
    success: async ({ confirm }) => {
      if (confirm) {
        await coupleStore.removeWish(wish.id)
        uni.showToast({ title: '已删除', icon: 'success' })
      }
    },
  })
}

onMounted(() => {
  if (!coupleStore.profile) {
    coupleStore.initProfile()
  }
})
</script>

<template>
  <view class="wishlist-container">
    <!-- 标签页 -->
    <view class="tabs-container">
      <view class="tabs">
        <view
          v-for="tab in tabs"
          :key="tab.value"
          class="tab-item"
          :class="{ active: activeTab === tab.value }"
          @click="activeTab = tab.value"
        >
          {{ tab.label }}
        </view>
      </view>
    </view>

    <!-- 添加按钮 -->
    <view class="add-btn-container">
      <wd-button
        type="primary"
        custom-class="add-btn"
        @click="showAddDialog = true"
      >
        <wd-icon name="add" size="16px" />
        添加愿望
      </wd-button>
    </view>

    <!-- 统计摘要 -->
    <view class="stats-summary">
      <view class="stat-item" @click="activeTab = 'all'">
        <view class="stat-num">
          {{ stats.total }}
        </view>
        <view class="stat-label">
          全部
        </view>
      </view>
      <view class="stat-item" @click="activeTab = 'pending'">
        <view class="stat-num">
          {{ stats.pending }}
        </view>
        <view class="stat-label">
          待实现
        </view>
      </view>
      <view class="stat-item" @click="activeTab = 'in-progress'">
        <view class="stat-num">
          {{ stats.doing }}
        </view>
        <view class="stat-label">
          进行中
        </view>
      </view>
      <view class="stat-item" @click="activeTab = 'completed'">
        <view class="stat-num">
          {{ stats.done }}
        </view>
        <view class="stat-label">
          已完成
        </view>
      </view>
    </view>

    <!-- 愿望列表 -->
    <view class="wishlist">
      <view
        v-for="wish in filteredWishlist"
        :key="wish.id"
        class="wish-item"
        :class="{ completed: wish.status === 'completed' }"
      >
        <view class="wish-header">
          <view class="category-icon" :style="{ color: getCategoryInfo(wish.category).color }">
            {{ getCategoryInfo(wish.category).icon }}
          </view>
          <view class="wish-content">
            <view class="wish-title">
              {{ wish.title }}
            </view>
            <view class="wish-meta">
              <wd-tag
                :color="getCategoryInfo(wish.category).color"
                size="small"
              >
                {{ getCategoryInfo(wish.category).label }}
              </wd-tag>
              <wd-tag
                :color="getPriorityColor(wish.priority)"
                size="small"
              >
                {{ priorities.find(p => p.value === wish.priority)?.label }}优先级
              </wd-tag>
            </view>
          </view>
          <view class="wish-actions">
            <view v-if="wish.targetDate" class="wish-date">
              {{ dayjs(wish.targetDate).format('MM月DD日') }}
            </view>
            <wd-button
              size="small"
              :type="wish.status === 'completed' ? 'success' : 'default'"
              style="margin-right: 6px;"
              @click="toggleWishStatus(wish)"
            >
              {{ getStatusText(wish.status) }}
            </wd-button>
            <wd-button size="small" plain @click="openActions(wish)">
              更多
            </wd-button>
          </view>
        </view>

        <!-- 进度条 -->
        <view class="progress-container">
          <wd-progress
            :percentage="getProgress(wish.status)"
            :color="wish.status === 'completed' ? '#2ed573' : '#4ecdc4'"
            :show-text="false"
            height="4px"
          />
        </view>

        <!-- 愿望描述 -->
        <view v-if="wish.description" class="wish-description">
          {{ wish.description }}
        </view>

        <!-- 愿望详情 -->
        <view class="wish-details">
          <view v-if="wish.cost" class="detail-item">
            <wd-icon name="money" size="14px" color="#666" />
            <text>预算：¥{{ wish.cost }}</text>
          </view>
          <view v-if="wish.completedDate" class="detail-item">
            <wd-icon name="check" size="14px" color="#2ed573" />
            <text>完成日期：{{ dayjs(wish.completedDate).format('MM月DD日') }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 编辑愿望弹窗 -->
    <wd-popup v-model="showEditDialog" position="bottom" :safe-area-inset-bottom="true">
      <view class="add-dialog">
        <view class="dialog-header">
          <view class="dialog-title">
            编辑愿望
          </view>
          <wd-icon name="close" @click="closeEdit" />
        </view>
        <view class="dialog-content">
          <wd-cell-group>
            <wd-input v-model="editWish.title" label="愿望标题" required />
            <wd-input v-model="editWish.description" label="愿望描述" />
            <wd-picker v-model="editWish.category" label="分类" :columns="categories" />
            <wd-picker v-model="editWish.priority" label="优先级" :columns="priorities" />
            <wd-cell title="目标日期" :value="editWish.targetDate || '请选择日期'" is-link @click="showEditDatePicker = true; tempTargetDate = editWish.targetDate ? dayjs(editWish.targetDate).valueOf() : Date.now()" />
            <wd-picker v-model="editWish.status" label="状态" :columns="tabs.filter(t => t.value !== 'all')" />
          </wd-cell-group>
        </view>
        <view class="dialog-actions">
          <wd-button @click="closeEdit">
            取消
          </wd-button>
          <wd-button type="primary" @click="submitEdit">
            保存
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 空状态 -->
    <view v-if="filteredWishlist.length === 0" class="empty-state">
      <wd-icon name="star" size="64px" color="#ccc" />
      <text class="empty-text">
        {{ activeTab === 'all' ? '还没有愿望，快去添加一个吧！' : `暂无${tabs.find(t => t.value === activeTab)?.label}的愿望` }}
      </text>
    </view>

    <!-- 添加愿望弹窗 -->
    <wd-popup
      v-model="showAddDialog"
      position="bottom"
      :safe-area-inset-bottom="true"
    >
      <view class="add-dialog">
        <view class="dialog-header">
          <view class="dialog-title">
            添加愿望
          </view>
          <wd-icon name="close" @click="showAddDialog = false" />
        </view>

        <view class="dialog-content">
          <wd-cell-group>
            <wd-input
              v-model="newWish.title"
              label="愿望标题"
              placeholder="请输入愿望标题"
              required
            />
            <wd-input
              v-model="newWish.description"
              label="愿望描述"
              placeholder="详细描述一下这个愿望"
            />
            <wd-picker
              v-model="newWish.category"
              label="分类"
              :columns="categories"
            />
            <wd-picker
              v-model="newWish.priority"
              label="优先级"
              :columns="priorities"
            />
            <wd-cell title="目标日期" :value="newWish.targetDate || '选择目标完成日期（可选）'" is-link @click="showDatePicker = true; tempTargetDate = newWish.targetDate ? dayjs(newWish.targetDate).valueOf() : Date.now()" />
            <wd-input
              v-model="newWish.cost"
              label="预算"
              type="number"
              placeholder="预计花费（可选）"
            />
          </wd-cell-group>
        </view>

        <view class="dialog-actions">
          <wd-button @click="showAddDialog = false">
            取消
          </wd-button>
          <wd-button type="primary" @click="handleAddWish">
            添加
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 日期选择器 -->
    <wd-popup v-model="showDatePicker" position="bottom">
      <wd-datetime-picker-view
        v-model="tempTargetDate"
        type="date"
      />
      <view class="picker-actions">
        <wd-button @click="showDatePicker = false">
          取消
        </wd-button>
        <wd-button type="primary" @click="handleDateConfirm">
          确定
        </wd-button>
      </view>
    </wd-popup>

    <!-- 编辑日期选择器 -->
    <wd-popup v-model="showEditDatePicker" position="bottom">
      <wd-datetime-picker-view
        v-model="tempTargetDate"
        type="date"
      />
      <view class="picker-actions">
        <wd-button @click="showEditDatePicker = false">
          取消
        </wd-button>
        <wd-button type="primary" @click="handleEditDateConfirm">
          确定
        </wd-button>
      </view>
    </wd-popup>

    <wd-toast />
  </view>
</template>

<style lang="scss" scoped>
.wishlist-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffb6c1 0%, #ffc0cb 50%, #ffb6c1 100%);
  padding-bottom: 100px;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 30% 30%, rgba(255, 182, 193, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 70% 70%, rgba(255, 192, 203, 0.3) 0%, transparent 50%);
    pointer-events: none;
  }
}

.tabs-container {
  background: white;
  padding: 0 16px;
  border-bottom: 1px solid #eee;

  .tabs {
    display: flex;

    .tab-item {
      flex: 1;
      text-align: center;
      padding: 16px 0;
      font-size: 14px;
      color: #666;
      border-bottom: 2px solid transparent;
      transition: all 0.3s;

      &.active {
        color: #ff69b4;
        border-bottom-color: #ff69b4;
        font-weight: 600;
      }
    }
  }
}

.add-btn-container {
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .add-btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }
}

.wishlist {
  padding: 0 16px;
}

.wish-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;

  &.completed {
    opacity: 0.8;

    .wish-title {
      text-decoration: line-through;
      color: #999;
    }
  }

  .wish-header {
    display: flex;
    align-items: flex-start;
    margin-bottom: 12px;

    .category-icon {
      font-size: 24px;
      margin-right: 12px;
      margin-top: 2px;
    }

    .wish-content {
      flex: 1;

      .wish-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 8px;
        line-height: 1.4;
      }

      .wish-meta {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
      }
    }

    .wish-actions {
      margin-left: 12px;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 8px;

      .wish-date {
        font-size: 14px;
        color: #666;
        font-weight: 500;
      }
    }
  }

  .progress-container {
    margin-bottom: 12px;
  }

  .wish-description {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
    margin-bottom: 12px;
  }

  .wish-details {
    .detail-item {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 12px;
      color: #666;
      margin-bottom: 4px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;

  .empty-text {
    margin-top: 16px;
    font-size: 14px;
    color: #999;
    text-align: center;
  }
}

.stats-summary {
  display: flex;
  padding: 16px;
  background: white;
  margin: 0 16px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .stat-item {
    flex: 1;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background: rgba(78, 205, 196, 0.1);
      border-radius: 8px;
    }

    .stat-num {
      font-size: 24px;
      font-weight: 600;
      color: #ff69b4;
      margin-bottom: 4px;
      text-shadow: 0 1px 3px rgba(255, 105, 180, 0.3);
    }

    .stat-label {
      font-size: 12px;
      color: #666;
    }
  }
}

.add-dialog {
  background: white;
  border-radius: 16px 16px 0 0;
  max-height: 80vh;

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #eee;

    .dialog-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .dialog-content {
    padding: 20px;
    max-height: 50vh;
    overflow-y: auto;
  }

  .dialog-actions {
    display: flex;
    gap: 12px;
    padding: 20px;
    border-top: 1px solid #eee;
  }
}

.picker-actions {
  display: flex;
  gap: 12px;
  padding: 20px;
  background: white;
  border-top: 1px solid #eee;
}
</style>
